package xyz.mimai.media.netty.tcp.bad;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName Client
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/4 9:34
 * @Version 1.0.0
 **/
public class Client {
    public static void main(String[] args) {
        //客户端只需要一个事件组就够了
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            //客户端启动对象
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new SelfDefineClientHandler());
                        }
                    });
            System.out.println("客户端启动完成，准备连接服务器...");
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7777).sync();
            sync.channel().closeFuture().sync();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

    public static class SelfDefineClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
        private AtomicInteger count=new AtomicInteger(1);
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("通道连接就绪，发送消息...");
            for(int inx=0;inx<10;inx++){
                String msg = "第"+(inx+1)+"个数据包\t";
                ByteBuf byteBuf= Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
                ctx.writeAndFlush(byteBuf);
            }
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            String recvContent  = msg.toString( CharsetUtil.UTF_8);
            System.out.println("第"+count.getAndAdd(1)+"次接收到Server消息，内容："+recvContent);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
          //  super.exceptionCaught(ctx, cause);
            System.out.println("发生了异常... ...");
            cause.printStackTrace();
            ctx.close();
        }
    }
}
